package com.hmjk.health.health;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.NetService;
import com.hmjk.health.util.BP_Evaluator;
import com.hmjk.health.util.BloodPressureData.BP_DETAIL;
import com.hmjk.health.util.GlycoseData;
import com.hmjk.health.util.GlycoseReferenceSet;
import com.hmjk.health.util.GlycoseData.GLY_DETAIL;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class GlycoseHistoryActivity extends Activity implements OnClickListener, OnScrollListener, OnTouchListener{
	private final String TAG = GlycoseHistoryActivity.class.getSimpleName();
	private HealthApp mApp = null;
	private String tid = null, subcode = null, nickname = null, uid = null;	
	private String entry = null;
	private ImageButton backBut;
	private TextView subAccName;
	private TextView selDate;
	private Button jourBut, chartBut;
	private ImageButton refreshBut;
	private ListView mList;
	private long from;
	private long to;
	private int pageIndex = 1;
	private final static int QUERY_PAGE_SIZE = 30;
	private int selyear, selmonth;
	private boolean getNext = false;
	private GlycoseReferenceSet mGlyRefSet = null;
	private ArrayList<GLY_DETAIL> mGlydataArray = new ArrayList<GLY_DETAIL>();
	private GlydataAdapter mGlydataAdapter = null;
	
	private ArrayList<BP_DETAIL> mBpDataArray = new ArrayList<BP_DETAIL>();
	private BpDataAdapter mBpDataAdapter = null;
	
	private void logd(String info){
		Log.d(TAG,info);
	}	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		uid = mApp.getUID();
		tid = getIntent().getExtras().getString("tid");	
		subcode = getIntent().getExtras().getString("subcode");
		nickname = getIntent().getExtras().getString("nickname");
		entry = getIntent().getExtras().getString("entry");

		setContentView(R.layout.glycose_history);
		
		TextView mTitle = (TextView)findViewById(R.id.title);
		if(entry.equalsIgnoreCase("gluc")){
			mTitle.setText(R.string.glycose_history);
		}else if(entry.equalsIgnoreCase("bp")){
			mTitle.setText(R.string.bp_history);
		}
		
		backBut = (ImageButton) this.findViewById(R.id.back);
		backBut.setOnClickListener(this);
		jourBut = (Button)this.findViewById(R.id.JournalBut);
		jourBut.setOnClickListener(this);
		chartBut = (Button)this.findViewById(R.id.ChartBut);
		chartBut.setOnClickListener(this);
		subAccName = (TextView) this.findViewById(R.id.subname);
		selDate = (TextView) this.findViewById(R.id.seldate);
		selDate.setOnClickListener(this);
		refreshBut = (ImageButton) this.findViewById(R.id.refreshbut);
		refreshBut.setOnClickListener(this);
		
		mList = (ListView) this.findViewById(R.id.list);		
		if(entry.equalsIgnoreCase("gluc")){
			mGlydataAdapter = new GlydataAdapter();
			mList.setAdapter(mGlydataAdapter);
		}else if(entry.equalsIgnoreCase("bp")){
			mBpDataAdapter = new BpDataAdapter();
			mList.setAdapter(mBpDataAdapter);
		}
		mList.setOnScrollListener(this);
		mList.setOnTouchListener(this);
		
		subAccName.setText(nickname);
		
		Time t = new Time();
		t.setToNow();
		selyear = t.year;
		selmonth = t.month;
		if((selmonth+1) < 10)	        						   
			 selDate.setText(Integer.toString(selyear)+"-"+"0"+Integer.toString(selmonth+1));
		else
			 selDate.setText(Integer.toString(selyear)+"-"+Integer.toString(selmonth+1));  
		
		String[] arg = {tid};		
		mGlyRefSet = (GlycoseReferenceSet) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_SET, arg);
	}
	
	public long getStartTime(int year, int mon)
	{
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, mon);
		c.set(Calendar.DATE, 1);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		
		return c.getTimeInMillis();
	}
	
	public long getEndTime(int year, int mon)
	{
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, mon+1);
		c.set(Calendar.DATE, 1);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		
		return c.getTimeInMillis();
	}	
	
	private void doSearchHistoryGlyData(){	
		mApp.showWaitting(this, null);
		//refreshImg.startAnimation(cycleAnim);
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.GET_GLYCOSE_HISTORY_DATA);
		si.putExtra("uid", uid);
		si.putExtra("tid", tid);
		si.putExtra("subcode", subcode);
		si.putExtra("endtime", to);
		si.putExtra("starttime", from);
		si.putExtra("pageindex", String.valueOf(pageIndex));
		si.putExtra("pagesize", String.valueOf(QUERY_PAGE_SIZE));
		
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_GLYCOSE_HISTORY_DATA" + t.toString();
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp, mHandler);
		startService(si);
		/*GLY_KEY key = new GLY_KEY(tid,subcode);
		mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_DATA,key);*/
	}
	
	private void doSearchHistoryBpData(){
		mApp.showWaitting(this, null);
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.GET_BP_HISTORY_DATA);
		si.putExtra("uid", uid);
		si.putExtra("tid", tid);
		si.putExtra("subcode", subcode);
		si.putExtra("endtime", to);
		si.putExtra("starttime", from);
		si.putExtra("pageindex", String.valueOf(pageIndex));
		si.putExtra("pagesize", String.valueOf(QUERY_PAGE_SIZE));
		
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_BP_HISTORY_DATA" + t.toString();
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp, mHandler);
		startService(si);
	}
	
	private boolean checkBgtypeValid(String type){
		try {
			int iType = Integer.parseInt(type);
			if((iType >= 1) && (iType <= 8)){
				return true;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case HealthApp.MSG_NET_RESPONSE:{
				logd("MSG_NET_RESPONSE");
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				if(stamp.startsWith("GET_GLYCOSE_HISTORY_DATA")){
					mApp.dismissWaiting();
					//refreshImg.clearAnimation();
					String sjson = b.getString("json");
					if(sjson != null){
						//mApp.dismissWaiting();
						getNext = false;
						
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							JSONObject sd = json.getJSONObject("senddata");
							if(sd != null)
								tid = sd.getString("tid");
							if(code == 200){
								String state = json.getString("state");
								if(state.equalsIgnoreCase("00")){
									if(pageIndex == 1){
										mGlydataArray.clear();
									}
									JSONObject recdata = json.getJSONObject("recdata");
									if(recdata != null){
										if(recdata.has("bgdata")){
											JSONArray arr = recdata.getJSONArray("bgdata");
											int len = arr.length();
											Log.d(TAG, "GET SIZE = " + len);
											if(len < QUERY_PAGE_SIZE){
												Log.d(TAG, "NO DATA MORE");
												getNext = false;
											}else{
												Log.d(TAG, "DATA MORE");
												getNext = true;
											}
											for(int i = 0; i < len; i++){
												JSONObject o = arr.getJSONObject(i);
												
												String bgvalue = o.getString("bgvalue");
												if(bgvalue.trim().isEmpty() || bgvalue.equalsIgnoreCase("NULL")){
													continue;
												}
												
												String bgtype = o.getString("bgtype");
												if(bgtype.trim().isEmpty() || bgtype.equalsIgnoreCase("NULL")){
													continue;
												}
												if(checkBgtypeValid(bgtype) == false){
													continue;
												}
												
												float value = Float.parseFloat(bgvalue);
												long time = o.getLong("recordtime");
												
												int type = Integer.parseInt(bgtype);
												
												GLY_DETAIL gly = new GLY_DETAIL(value, time, type);
												mGlydataArray.add(gly);
											}
										}else{
											Log.d(TAG, "2 NO DATA MORE");
											getNext = false;
										}
									}
									mGlydataAdapter.notifyDataSetChanged();
								}else if(state.equals("01")){
									if(pageIndex == 1){
										mGlydataArray.clear();
									}
									mGlydataAdapter.notifyDataSetChanged();
									mApp.showAlertDialog(GlycoseHistoryActivity.this, R.string.server_noResp);
								}
								return;
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if(pageIndex == 1){
							mGlydataArray.clear();
							mGlydataAdapter.notifyDataSetChanged();
						}
						
						mApp.showAlertDialog(GlycoseHistoryActivity.this, R.string.history_err);
					}
				}else if(stamp.startsWith("GET_BP_HISTORY_DATA")){
					mApp.dismissWaiting();
					String sjson = b.getString("json");
					if(sjson != null){
						getNext = false;
						
						try {
							
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							JSONObject sd = json.getJSONObject("senddata");
							if(sd != null)
								tid = sd.getString("tid");
							if(code == 200){
								String state = json.getString("state");
								if(state.equalsIgnoreCase("00")){
									
									if(pageIndex == 1){
										mBpDataArray.clear();
									}
									JSONObject recdata = json.getJSONObject("recdata");
									if(recdata != null){
										
										if(recdata.has("bpdata")){
											
											JSONArray arr = recdata.getJSONArray("bpdata");
											int len = arr.length();
											Log.d(TAG, "GET SIZE = " + len);
											if(len < QUERY_PAGE_SIZE){
												Log.d(TAG, "NO DATA MORE");
												getNext = false;
											}else{
												Log.d(TAG, "DATA MORE");
												getNext = true;
											}
											
											for(int i = 0; i < len; i++){
												JSONObject o = arr.getJSONObject(i);
												
												String sbpString = o.getString("sbp");
												if(sbpString.trim().isEmpty() || sbpString.equalsIgnoreCase("NULL")){
													continue;
												}
												
												String dbpString = o.getString("dbp");
												if(dbpString.trim().isEmpty() || dbpString.equalsIgnoreCase("NULL")){
													continue;
												}
												
												String pulseString = o.getString("pulse");
												if(pulseString.trim().isEmpty() || pulseString.equalsIgnoreCase("NULL")){
													continue;
												}
												
												long time = o.getLong("recordtime");
												
												BP_DETAIL bp = new BP_DETAIL(Integer.parseInt(sbpString), Integer.parseInt(dbpString), Integer.parseInt(pulseString), time);
												mBpDataArray.add(bp);
											}
											
										}else{
											Log.d(TAG, "2 NO DATA MORE");
											getNext = false;
										}
										
									}
									mBpDataAdapter.notifyDataSetChanged();
									
								}else if(state.equals("01")){
									if(pageIndex == 1){
										mBpDataArray.clear();
									}
									mBpDataAdapter.notifyDataSetChanged();
									mApp.showAlertDialog(GlycoseHistoryActivity.this, R.string.server_noResp);
								}
								return;
							}
							
						} catch (JSONException e) {
							// TODO: handle exception
							e.printStackTrace();
						}
						if(pageIndex == 1){
							mBpDataArray.clear();
							mBpDataAdapter.notifyDataSetChanged();
						}
						
						mApp.showAlertDialog(GlycoseHistoryActivity.this, R.string.history_err);
					}
				}
			}break;
			}
		}
	};
	
	private String getDay(long time)
	{
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(time);
		return (String) DateFormat.format("yyyy-MM-dd", c);
	}
	
	private String getTimeStr(long time)
	{
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(time);
		return (String) DateFormat.format("yyyy-MM-dd h:mmaa", c);
		//return Long.toString(time) + " "+DateFormat.format("yyyy-MM-dd hh:mm", c);
	}
     	
	private int btTypeRes[] = {R.string.gluc_before_dawn,
			R.string.gluc_empty_stomach,
			R.string.gluc_after_breakfast,
			R.string.gluc_before_lunch,
			R.string.gluc_after_lunch,
			R.string.gluc_before_dinner,
			R.string.gluc_after_dinner,
			R.string.gluc_at_bedtime};
	
	class GlydataAdapter extends BaseAdapter{
		class ViewHolder{
			public TextView dateIndex;
			public TextView timedate;
			public TextView type;
			public TextView value;
			public TextView uint;
		}
		
		@Override
		public int getCount() {
			return mGlydataArray.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mGlydataArray.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		private int getColorIndex(float mmol, int type){
			float low = 4.4f;
			float up = 8.0f;
			if(type == GlycoseData.TYPE_GLUC_BEFORE_DAWN){
				low = mGlyRefSet.dawnlow;
				up = mGlyRefSet.dawnupper;
			}else if((type == GlycoseData.TYPE_GLUC_EMPTY_STOMACH) ||
					(type == GlycoseData.TYPE_GLUC_BEFORE_LUNCH) || (type == GlycoseData.TYPE_GLUC_BEFORE_DINNER)){
				low = mGlyRefSet.beforelow;
				up = mGlyRefSet.bedtimeupper;
			}else if((type == GlycoseData.TYPE_GLUC_AFTER_BREAKFAST) ||
					(type == GlycoseData.TYPE_GLUC_AFTER_LUNCH) || (type == GlycoseData.TYPE_GLUC_AFTER_DINNER)){
				low = mGlyRefSet.afterlow;
				up = mGlyRefSet.afterupper;
			}else if(type == GlycoseData.TYPE_GLUC_AT_BEDTIME){
				low = mGlyRefSet.bedtimelow;
				up = mGlyRefSet.bedtimeupper;
			}
			
			if(mmol < low){
				return R.color.FOREGROUND_YELLOW;
			}else if(mmol > up){
				return R.color.HIGHLIGHT_RED;
			}else{
				return R.color.LIGHT_GREEN;
			}
			
		}
		
		@Override
		public View getView(int pos, View itemView, ViewGroup group) {
			ViewHolder holder;
			
			if(itemView == null){
				LayoutInflater inflater = getLayoutInflater();
				itemView = inflater.inflate(R.layout.glycose_history_item, null);
				holder = new ViewHolder();
				
				holder.dateIndex = (TextView)itemView.findViewById(R.id.dateStr);
				holder.timedate = (TextView)itemView.findViewById(R.id.itemTime);
				holder.type = (TextView)itemView.findViewById(R.id.itemType);
				holder.value = (TextView)itemView.findViewById(R.id.itemValue);
				holder.uint = (TextView)itemView.findViewById(R.id.itemUnit);
				itemView.setTag(holder);
			}else{
				holder = (ViewHolder)itemView.getTag();
			}
			

				GLY_DETAIL e = mGlydataArray.get(pos);
				String indexS = getDay(e.recordTime);
				holder.dateIndex.setText(indexS);
				holder.timedate.setText(getTimeStr(e.recordTime));
				holder.type.setText(btTypeRes[e.bgtype-1]);
				String sglucvalue = null;
				if((mGlyRefSet != null) && (mGlyRefSet.unit == 0)){// mg/dL
					int mgdl = (int) (e.bgvalue * 18);
					sglucvalue = String.valueOf(mgdl);
					holder.uint.setText("mg/dL");
				}else{
					sglucvalue = String.valueOf(e.bgvalue);
					holder.uint.setText("mmol/L");
				}
				int colorIndex = getColorIndex(e.bgvalue, e.bgtype);
				holder.value.setTextColor(getResources().getColor(colorIndex));
				holder.uint.setTextColor(getResources().getColor(colorIndex));
				holder.value.setText(sglucvalue);
				
				if(pos > 0)
				{
					GLY_DETAIL e1 = mGlydataArray.get(pos-1);
					if(getDay(e1.recordTime).equals(indexS))
					{
						holder.dateIndex.setVisibility(View.GONE);
					}
					else
					{
						holder.dateIndex.setVisibility(View.VISIBLE);
					}
					
				}
				else
					holder.dateIndex.setVisibility(View.VISIBLE);
			return itemView;
		}
	
	}
	
	class BpDataAdapter extends BaseAdapter{
		class ViewHolder{
			public TextView mTime;
			public TextView mBpValue;
			public TextView mHintText;
			public ImageView mHintImg;
			public TextView mPulse;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mBpDataArray.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mBpDataArray.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int pos, View itemView, ViewGroup group) {
			ViewHolder holder;
			
			if(itemView == null){
				LayoutInflater inflater = getLayoutInflater();
				itemView = inflater.inflate(R.layout.bp_history_item, null);
				holder = new ViewHolder();
				
				holder.mTime = (TextView)itemView.findViewById(R.id.itemTime);
				holder.mBpValue = (TextView)itemView.findViewById(R.id.value);
				holder.mHintText = (TextView)itemView.findViewById(R.id.hint);
				holder.mPulse = (TextView)itemView.findViewById(R.id.pulse);
				holder.mHintImg = (ImageView)itemView.findViewById(R.id.hintimage);
				
				itemView.setTag(holder);
			}else {
				holder = (ViewHolder) itemView.getTag();
			}
			
			BP_DETAIL e = mBpDataArray.get(pos);
			String indexS = getTimeStr(e.recordtime);
			holder.mTime.setText(indexS);
			
			int r = BP_Evaluator.evaluateLevel(e.sbp, e.dbp).type;
			int color = getResources().getColor(R.color.BP_LBP);;
			switch (r) {
			case BP_Evaluator.TYPE_LOW:{
				color = getResources().getColor(R.color.BP_LBP);
				indexS = getResources().getString(R.string.bp_lvl_lbp);
				holder.mHintImg.setImageDrawable(getResources().getDrawable(R.drawable.health_toolow));
				holder.mHintImg.setVisibility(View.VISIBLE);
			}break;

			case BP_Evaluator.TYPE_NORMAL:{
				color = getResources().getColor(R.color.BP_NOR);
				indexS = getResources().getString(R.string.bp_lvl_normal);
				holder.mHintImg.setVisibility(View.INVISIBLE);
			}break;
			
			case BP_Evaluator.TYPE_NORMALHIGH:{
				color = getResources().getColor(R.color.BP_NOR_HIGH);
				indexS = getResources().getString(R.string.bp_lvl_normal_high);
				holder.mHintImg.setVisibility(View.INVISIBLE);
			}break;
			
			case BP_Evaluator.TYPE_1HIGH:{
				color = getResources().getColor(R.color.BP_HBP_I);
				indexS = getResources().getString(R.string.bp_lvl_hbp_mild);
				holder.mHintImg.setImageDrawable(getResources().getDrawable(R.drawable.health_toohigh));
				holder.mHintImg.setVisibility(View.VISIBLE);
			}break;
			
			case BP_Evaluator.TYPE_2HIGH:{
				color = getResources().getColor(R.color.BP_HBP_II);
				indexS = getResources().getString(R.string.bp_lvl_hbp_moderate);
				holder.mHintImg.setImageDrawable(getResources().getDrawable(R.drawable.health_toohigh));
				holder.mHintImg.setVisibility(View.VISIBLE);
			}break;
			
			case BP_Evaluator.TYPE_3HIGH:{
				color = getResources().getColor(R.color.BP_HBP_III);
				indexS = getResources().getString(R.string.bp_lvl_hbp_severe);
				holder.mHintImg.setImageDrawable(getResources().getDrawable(R.drawable.health_toohigh));
				holder.mHintImg.setVisibility(View.VISIBLE);
			}break;
			}
			holder.mHintText.setText(indexS);
			
			indexS = "" + e.sbp + "/" + e.dbp;
			holder.mBpValue.setTextColor(color);
			holder.mBpValue.setText(indexS);
			
			holder.mPulse.setText("" + e.pulse);
			
			return itemView;
		}
		
	}
	
	  private void hidDay(DatePicker mDatePicker) {
	         Field[] datePickerfFields = mDatePicker.getClass().getDeclaredFields();
	         for (Field datePickerField : datePickerfFields) {
	             if ("mDaySpinner".equals(datePickerField.getName())) {
	                 datePickerField.setAccessible(true);
	                 Object dayPicker = new Object();
	                 try {
	                     dayPicker = datePickerField.get(mDatePicker);
	                 } catch (IllegalAccessException e) {
	                     e.printStackTrace();
	                 } catch (IllegalArgumentException e) {
	                     e.printStackTrace();
	                 }
	                 // datePicker.getCalendarView().setVisibility(View.GONE);
	                 ((View) dayPicker).setVisibility(View.GONE);
	             }
	         }
	     }	
	
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.back:
			this.finish();
			break;
		case R.id.refreshbut:{
			from = getStartTime(selyear, selmonth);
			to = getEndTime(selyear, selmonth);
			pageIndex = 1;
			if(entry.equalsIgnoreCase("gluc")){
				doSearchHistoryGlyData();
			}else if(entry.equalsIgnoreCase("bp")){
				doSearchHistoryBpData();
			}
		}break;
		case R.id.seldate:
		{	
	           Builder builder = new AlertDialog.Builder(this);  
				LayoutInflater inflater = getLayoutInflater();
				View view = inflater.inflate(R.layout.datepick, null);
				final DatePicker dateV = (DatePicker) view.findViewById(R.id.datePicker);
				hidDay(dateV);
				dateV.updateDate(selyear,selmonth,1);
	           builder.setView(view);
	            DialogInterface.OnClickListener btnListener =   
	                    new DialogInterface.OnClickListener() {  
	                        @Override  
	                        public void onClick(DialogInterface dialogInterface, int which) { 
	                        	int y = dateV.getYear();
	                        	int m = dateV.getMonth();
	                        	if(selyear != y || selmonth != m)
	                        	{
	        					   selyear = y;
	        					   selmonth = m;
	        					   if((selmonth+1) < 10)	        						   
	        					     selDate.setText(Integer.toString(selyear)+"-"+"0"+Integer.toString(selmonth+1));
	        					   else
	        					     selDate.setText(Integer.toString(selyear)+"-"+Integer.toString(selmonth+1));   
	                        	}
	                        	
	                        }  
	                    };  
	                builder.setPositiveButton(getResources().getString(R.string.ok), btnListener);  
	                builder.setNegativeButton(getResources().getString(R.string.Cancel), null);
	                Dialog dialog = builder.create();  		
	                dialog.show();	           
		}
		break;
		case R.id.JournalBut:
		{
			long lateTime = System.currentTimeMillis() -  mApp.getGlycoseQueryLatestMaxDays()*24*60*60*1000;
			Calendar ca = Calendar.getInstance();
			ca.setTimeInMillis(lateTime);
			ca.set(Calendar.MINUTE, 0);
			ca.set(Calendar.SECOND, 0);
			lateTime = ca.getTimeInMillis();
			lateTime ++;
		}
		break;
		case R.id.ChartBut:
		{
			
		}
		break;
		}
	}
		
	/*OnScrollListener start*/
	private boolean listBottom = false;
	@Override
	public void onScroll(AbsListView arg0, int firstV, int vCount, int total) { 
		 if(margin > 0)
			 return;
		 
         if (firstV + vCount == total && total > 0) { 
        	 int lb = mList.getBottom();
        	 int lt = mList.getTop();
        	 int count = mList.getChildCount();
        	 View bottomView = mList.getChildAt(count -1);
        	 int bb = bottomView.getBottom();
        	 bb += lt;
        	 //int bt = bottomView.getTop();
        	 if (lb >= bb){
        		 if(!listBottom){		
	        		 listBottom = true;  
	        		 Log.d("PULL_DEBUG", "LIST BOTTOM");
	        	 }
             }else{
            	if(listBottom){
        			 listBottom=false;
        			 Log.d("PULL_DEBUG", "NOT LIST BOTTOM");
        		} 
             }

         }else{
        	 if(listBottom){
        	 listBottom=false;
        	 Log.d("PULL_DEBUG", "NOT LIST BOTTOM");
        	 }
         }  
	}  

	@Override
	public void onScrollStateChanged(AbsListView v, int scrollState) {
		Log.d("PULL_DEBUG", "scrollState = "+ scrollState);
	}
	/*OnScrollListener end*/

	/*OnTouchListener start*/
	private float down_y=0f;
	//private boolean pull = false;
	private int margin = 0;
	@Override
	public boolean onTouch(View v, MotionEvent e) {
		
        float density = getResources().getDisplayMetrics().density; 
        LinearLayout.LayoutParams pullLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
        		LinearLayout.LayoutParams.WRAP_CONTENT);  
        Log.d("PULL_DEBUG", "TOUCH ACTION="+e.getAction());
        switch(e.getAction()){  
        case MotionEvent.ACTION_DOWN:   
            down_y = e.getY();
            break;  
        case MotionEvent.ACTION_MOVE:  
        	float y_dis = down_y - e.getY(); 
        	y_dis = y_dis/4;
        	Log.d("PULL_DEBUG", "dis="+y_dis+" listBottom="+listBottom);
        	if(listBottom && y_dis > 0){  		
        		Log.d("PULL_DEBUG", "PULL DOWN");
        		float distance=Math.abs(y_dis/density + 0.5f);  
        		pullLp.bottomMargin = margin =(int)distance;  
        		Log.d("PULL_DEBUG", "PULL DOWN margin= "+margin);
                mList.setLayoutParams(pullLp);  
              
        	}else if(margin > 0){
        		pullLp.bottomMargin = margin = 0;  
    			mList.setLayoutParams(pullLp);
        		Log.d("PULL_DEBUG", "NOT PULL DOWN");
        		//pull = false;
        	}
        	break;  
        case MotionEvent.ACTION_UP: 
        case MotionEvent.ACTION_CANCEL:
        	if(margin > 0){
        		//if(listBottom){  
        		if(margin > 40){
        			if(!getNext){
                		Log.d("PULL_DEBUG", "NO NEXT");
                	}else{
                		Log.d("PULL_DEBUG", "CHECKING..");
                		pageIndex++;
                		
                		if(entry.equalsIgnoreCase("gluc")){
                			doSearchHistoryGlyData();
                		}else if(entry.equalsIgnoreCase("bp")){
                			doSearchHistoryBpData();
                		}
                	}
        		}
        			pullLp.bottomMargin = margin = 0;  
        			mList.setLayoutParams(pullLp);
        			
        			
               // }   
        		
        	}
        	//pull = false;
        	//listBottom = false;
            break;  
        }  
        
		return false;
	}
	/*OnTouchListener end*/	
}